package com.designpattern.softwaredesignpatternstudy.pattern.singleton;

/**
 * @Author: Jiangxx
 * @Date: 2021/09/28
 * @Description: 用懒汉式单例模式模拟产生美国当今总统对象。
 */
public class SingletonLazy {
    public static void main(String[] args) {
        President zt1 = President.getPresidentInstance();
        zt1.getName();
        President zt2 = President.getPresidentInstance();
        zt2.getName();
        if (zt1 == zt2) {
            System.out.println("他们是同一个总统");
        } else {
            System.out.println("他们不是同一个总统");
        }
    }
}

class President {
    public static volatile President president = null;

    private President() {
        System.out.println("产生一个总统");
    }

    public static synchronized President getPresidentInstance() {
        if (president == null) {
            president =  new President();
        } else {
            System.out.println("已经有一个总统了");
        }
        return president;
    }

    public void getName() {
        System.out.println("我是美国总统：特朗普");
    }
}
